/**
 * Created by XianTao on 2016/11/9
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.jpa.base.util;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class SearchFilter {
    public String fieldName;
    public Operator operator;
    public Object value;

    public SearchFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.operator = operator;
        this.value = value;
    }

    /**
     * searchParams中key的格式为OPERATOR_FIELDNAME
     */
    public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
        for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
            //过滤空值
            String key = entry.getKey();
            Object value = entry.getValue();
            if (StringUtils.isEmpty(value)) {
                continue;
            }

            //拆分operator与filedAttribute
            String[] names = StringUtils.split(key, "_");
            if (names.length != 2) {
                throw new IllegalArgumentException(key + " is not a valid search filter name");
            }
            String fieldName = names[1];
            Operator operator = Operator.valueOf(names[0]);

            //创建searchFilter
            SearchFilter filter = new SearchFilter(fieldName, operator, value);
            filters.put(key, filter);
        }
        return filters;
    }

    public enum Operator {
        EQ, LIKE, LEFT_LIKE, RIGHT_LIKE, GT, LT, GTE, LTE, ISNULL, ISNOTNULL
    }
}
